/**
 * @Author:Kindear
 * @Date:2021-09-06
 * @Desc:用户绑定登录云函数
 */
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const axios = require('axios');
const TimeUtil = require('./timeutil');
const USER = 'edu-cloud-users'
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID;
  let action = event.action;
  switch(action){
    case 'findById':{
      // 根据ID 查询  
      let docId = event.docId;
      try {
        return await db.collection(USER).doc(docId).get();
      } catch (error) {
        return {
          errCode:-1,
          errMsg:'查询不到用户信息'
        }
      }
  
      break
    }
    case 'userBind':{
      // 获取用户信息
      let userInfo = event.userInfo;
      // 获取学号 密码相关信息
      let bindId = event.bindId;
      let bindPwd = event.bindPwd;
      // 调用 教务系统接口
      let authRes = await cloud.callFunction({
        name:'edu-cloud-api',
        data:{
          action:'authUser',
          xh:bindId,
          password:bindPwd
        }
      })
      // 获取返回结果
      let authData = authRes.result;
      if(authData.status!=200){
        return {
          errCode:-1,
          errMsg:'网络错误'
        }
      }else if(authData.data.flag == '1' || authData.data.flag == 1 || authData.data.flag == true){
        /** 登录成功 更新用户信息 */
        let matchRes = await db.collection(USER).where({
          openid
        }).get();
        //TODO
        /**调用执行获取全部课表接口 */

        // 新建
        if(matchRes.data.length == 0){
          db.collection(USER).add({
            data:{
              avatarUrl:userInfo.avatarUrl,
              nickName:userInfo.nickName,
              realName:authData.data.userrealname,
              userUnity:authData.data.userdwmc,
              userType:authData.data.usertype,
              openid:openid,
              bindId,
              bindPwd,
              token:authData.data.token,
              _createTime:TimeUtil.TimeCode(),
              _updateTime:TimeUtil.TimeCode()
            }
          })
        }else{
          //更新
          let baseData = matchRes.data[0]
          let docId = baseData._id;
          db.collection(USER).doc(docId).update({
            data:{
              avatarUrl:userInfo.avatarUrl,
              nickName:userInfo.nickName,
              realName:authData.data.userrealname,
              userUnity:authData.data.userdwmc,
              userType:authData.data.usertype,
              openid:openid,
              bindId,
              bindPwd,
              token:authData.data.token,
              _updateTime:TimeUtil.TimeCode()
            }
          })
        }
        return {
          errCode:0,
          errMsg:authData.data.msg
        }
      }else{
        return {
          errMsg:-1,
          errMsg:authData.data.msg
        }
      }
      break
    }
  }
}